package com.bitcat.firstapp.demo

import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.demo.intentdemo.Person
import com.google.gson.Gson
import es.dmoral.toasty.Toasty

class SpDemoActivity : AppCompatActivity() {

    //方式一  定义
    private lateinit var sp: SharedPreferences

    //方式二
//    private val sp by lazy { getSharedPreferences("sp_demo", MODE_PRIVATE) }

    //方式三 错误写法 ❎
//    private val sp:SharedPreferences = getSharedPreferences("sp_demo", MODE_PRIVATE)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_sp_demo)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        sp = getSharedPreferences("sp_demo", MODE_PRIVATE)
    }

    fun saveData(view: View) {
        //方式一 传统方式
//        val editor = sp.edit()
//        editor.putString("name", "bitcat")
//        editor.putInt("age", 18)
//        editor.putBoolean("isMale", true)
//        editor.apply()



        sp.edit {
            putString("name", "bitcat")
            putInt("age", 18)
            putBoolean("isMale", true)
            putString("person",Gson().toJson(Person("zhangsan",18)))
        }

        Toasty.success(this, "保存成功", Toasty.LENGTH_SHORT).show()
    }
    fun readData(view: View) {
        val name = sp.getString("name", "")
        val age = sp.getInt("age", 0)
        val isMale = sp.getBoolean("isMale", false)
        Toasty.info(this, "name:$name, age:$age, isMale:$isMale", Toasty.LENGTH_SHORT).show()
    }

    fun saveData2(view: View) {
        val list = listOf(
            Person("zhangsan",18),
            Person("lisi",19),
            Person("wangwu",20)
        )
        sp.edit {
//            putString("person",Gson().toJson(Person("zhangsan",18)))

            putString("personList",Gson().toJson(list))
        }

        Toasty.success(this, "保存成功", Toasty.LENGTH_SHORT).show()

    }
    fun readData2(view: View) {
//        val str = sp.getString("person","")
//        val person = Gson().fromJson(str,Person::class.java)
//        Toasty.info(this,"对象类型：${person.name}").show()

        val str = sp.getString("personList","")
        val list = Gson().fromJson(str,Array<Person>::class.java).toList()
        println(list)
    }

    fun clearData(view: View) {
        sp.edit {
//            remove("name")

            clear()
        }
    }
}